import 'dart:math';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/config/sqflite/user_db_provider.dart';
import 'package:flutter_douban/main_page/home/h5_detail_page/activity_detail_page.dart';
import 'package:flutter_douban/main_page/me/page/register_page.dart';
import 'package:flutter_douban/main_page/me/view/code_login_view.dart';
import 'package:flutter_douban/tool_views/app_dialog.dart';
import 'package:flutter_douban/tool_views/back_nav_btn.dart';
import 'package:flutter_douban/tool_views/ios_loading_dialog.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CodeLoginPage extends StatefulWidget {
  const CodeLoginPage({Key? key}) : super(key: key);

  @override
  _CodeLoginPageState createState() => _CodeLoginPageState();
}

class _CodeLoginPageState extends State<CodeLoginPage> {
  FocusNode blankNode = FocusNode();
  late TextEditingController _phoneTextEditingController;
  late TextEditingController _codeTextEditingController;
  String _codeStr = '';
  String _phoneStr = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _phoneTextEditingController = TextEditingController();
    _codeTextEditingController = TextEditingController();

    _phoneTextEditingController.addListener(() {
      setState(() {
        _phoneStr = _phoneTextEditingController.text;
      });
    });
    _codeTextEditingController.addListener(() {
      setState(() {
        _codeStr = _codeTextEditingController.text;
      });
    });
  }

  /// 获取验证码方法
  void getCodeMethond() {
    /// 随机数生成类
    var rng = new Random();
    String numStr = '';
    for (var i = 0; i < 6; i++) {
      //生成6个随机数
      numStr = numStr + rng.nextInt(10).toString(); //0-9
    }

    /// 验证码赋值
    _codeTextEditingController.text = numStr;
  }

  ///登录
  void loginMethoned() {
    if (_phoneTextEditingController.text.isEmpty) {
      AppDialog.showText(context, title: "请输入您的电话号码~");
      return;
    }

    if (_phoneTextEditingController.text.isNotEmpty &&
        _phoneTextEditingController.text.length != 11) {
      AppDialog.showText(context, title: "请输入正确的电话号码~");
      return;
    }

    if (_codeTextEditingController.text.isEmpty) {
      AppDialog.showText(context, title: "请输入您的验证码~");
      return;
    }

    if (_phoneTextEditingController.text.isNotEmpty &&
        _phoneTextEditingController.text.length == 11) {
      /// 展示loading
      Loading.show(context);

      UserDbProvider provider = new UserDbProvider();
      List _list;

      /// 查询是否为注册用户
      provider.getUserData(_phoneStr).then((value) => {
            _list = value,
            if (_list.length == 0)
              {
                /// 用户未注册
                AppDialog.showText(context, title: "账户未注册,请先去注册~"),
                Loading.hide(context),
              }
            else
              {
                /// 用户已经注册,登录
                AppDialog.showText(context, title: "登录成功~"),
                Future.delayed(const Duration(milliseconds: 1000), () async {
                  Loading.hide(context);
                  /// 本地缓存用户信息
                  SharedPreferences prefs =
                      await SharedPreferences.getInstance();
                  await prefs.setString(AppConfig.numberId, _phoneStr);
                  /// 发送登录成功通知
                  EventBusUtil.fire(LoginEvent(LoginEvent.logIn));
                  /// 返回根式图控制器
                  Navigator.pop(context);
                }),
              }
          });
      return;
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _phoneTextEditingController.dispose();
    _codeTextEditingController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leadingWidth: 45,
          leading: BackNavBtn(),
          actions: [
            IconButton(
                onPressed: () {
                  Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                    return ActivityDetail(
                      url:
                          'https://m.douguo.com/help/vip?open=0&aggressive=QrDdqKtzWQ&clientkey=2895b5a15d4202ab&app-state=0&device=iPhone9,1&device_id=13CB3E69-C216-4B9B-A995-1946AB7B9699&imei=4926D5D3-18DB-48D7-B85A-D065350C3BA5&pset=1&sdk=14.4&timestamp=1637654506&version=7100',
                      titleStr: '账号和VIP权益',
                    );
                  }));
                },
                alignment: Alignment.centerLeft,
                icon: Image.asset(
                  'assets/images/common/login_help@2x.png',
                  width: 22,
                  height: 22,
                  color: Colors.black,
                )),
          ],
        ),
        body: Container(
          color: Colors.white,
          child: GestureDetector(
              onTap: () {
                // 点击空白页面关闭键盘
                FocusScope.of(context).requestFocus(blankNode);
              },
              child: SingleChildScrollView(
                child: Container(
                  color: Colors.white,
                  height: MediaQuery.of(context).size.height,
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.only(left: 30, right: 30),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 20,
                      ),
                      Text(
                        '验证码登录',
                        style: TextStyle(
                            fontSize: 26,
                            fontWeight: FontWeight.bold,
                            color: Colors.black),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        'Hi,欢迎来到豆果美食会做饭很酷~',
                        style: TextStyle(fontSize: 14, color: Colors.black26),
                      ),
                      SizedBox(
                        height: 60,
                      ),
                      Row(
                        children: [
                          Row(
                            children: [
                              Text(
                                '+86',
                                style: TextStyle(
                                    fontSize: 15, color: Colors.black),
                              ),
                              SizedBox(
                                width: 5,
                              ),
                              Image.asset(
                                'assets/images/common/icon_topic_down@2x.png',
                                width: 14,
                                height: 14,
                                color: Colors.black,
                              )
                            ],
                          ),
                          SizedBox(
                            width: 10,
                          ),
                          Container(
                            height: 60,
                            width: MediaQuery.of(context).size.width - 160,
                            alignment: Alignment.center,
                            child: TextField(
                              autofocus: true,
                              keyboardType: TextInputType.number,
                              controller: _phoneTextEditingController,
                              decoration: InputDecoration.collapsed(
                                  hintText: '请输入手机号',
                                  hintStyle: TextStyle(
                                    fontSize: 13,
                                  )),
                            ),
                          )
                        ],
                      ),
                      Container(
                        height: 1,
                        color: AppColors.line,
                      ),
                      Row(
                        children: [
                          Container(
                            height: 60,
                            width: MediaQuery.of(context).size.width - 150,
                            color: Colors.white,
                            alignment: Alignment.center,
                            child: TextField(
                              autofocus: true,
                              controller: _codeTextEditingController,
                              decoration: InputDecoration.collapsed(
                                  hintText: '请输入验证码',
                                  hintStyle: TextStyle(
                                    fontSize: 13,
                                  )),
                            ),
                          ),
                          LoginFormCode(
                              onTapCallback: getCodeMethond,
                              available: _phoneStr.length == 11 ? true : false),
                        ],
                      ),
                      Container(
                        height: 1,
                        color: AppColors.line,
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      InkWell(
                        child: Container(
                          alignment: Alignment.center,
                          height: 44,
                          width: MediaQuery.of(context).size.width,
                          decoration: BoxDecoration(
                            color: (_phoneStr.length > 0 && _codeStr.length > 0)
                                ? AppColors.yellow
                                : AppColors.line,
                            borderRadius: BorderRadius.circular(22),
                          ),
                          child: Text(
                            '登录',
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: (_phoneStr.length > 0 &&
                                        _codeStr.length > 0)
                                    ? AppColors.black
                                    : AppColors.qianTextColor),
                          ),
                        ),
                        onTap: loginMethoned,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          InkWell(
                            child: Container(
                              alignment: Alignment.centerRight,
                              height: 60,
                              color: Colors.white,
                              child: Text(
                                '密码登录',
                                style: TextStyle(
                                    fontSize: 15, color: AppColors.black),
                              ),
                            ),
                            onTap: () {
                              Navigator.pop(context);
                            },
                          ),
                          InkWell(
                            child: Container(
                              alignment: Alignment.centerRight,
                              height: 60,
                              color: Colors.white,
                              child: Text(
                                '注册',
                                style: TextStyle(
                                    fontSize: 15, color: AppColors.black),
                              ),
                            ),
                            onTap: () {
                              Navigator.of(context)
                                  .push(MaterialPageRoute(builder: (_) {
                                return RegisterPage();
                              }));
                            },
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Text(
                        '其他登录方式',
                        style: TextStyle(fontSize: 14, color: AppColors.black),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Row(
                        children: [
                          IconButton(
                              padding: EdgeInsets.all(0),
                              alignment: Alignment.centerLeft,
                              onPressed: () {},
                              icon: Image.asset(
                                'assets/images/common/login_wechat@2x.png',
                                width: 30,
                                height: 30,
                              )),
                          SizedBox(
                            width: 15,
                          ),
                          IconButton(
                              padding: EdgeInsets.all(0),
                              alignment: Alignment.centerLeft,
                              onPressed: () {},
                              icon: Image.asset(
                                'assets/images/common/login_qq@2x.png',
                                width: 30,
                                height: 30,
                              )),
                          SizedBox(
                            width: 15,
                          ),
                          IconButton(
                              padding: EdgeInsets.all(0),
                              alignment: Alignment.centerLeft,
                              onPressed: () {},
                              icon: Image.asset(
                                'assets/images/common/login_sina@2x.png',
                                width: 30,
                                height: 30,
                              )),
                        ],
                      ),
                      Container(
                        padding: EdgeInsets.only(top: 10),
                        height: 120,
                        color: Colors.white,
                        child: RichText(
                          text: TextSpan(children: [
                            TextSpan(
                              text: '登录即同意 ',
                              style: TextStyle(
                                  color: Colors.black45, fontSize: 14),
                            ),
                            TextSpan(
                                text: '《联通/移动统一认证服务条款》',
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    Navigator.of(context)
                                        .push(MaterialPageRoute(builder: (_) {
                                      return ActivityDetail(
                                        url:
                                            'https://m.douguo.com/help/vip?open=0&aggressive=QrDdqKtzWQ&clientkey=2895b5a15d4202ab&app-state=0&device=iPhone9,1&device_id=13CB3E69-C216-4B9B-A995-1946AB7B9699&imei=4926D5D3-18DB-48D7-B85A-D065350C3BA5&pset=1&sdk=14.4&timestamp=1637654506&version=7100',
                                        titleStr: '联通/移动统一认证服务条款',
                                      );
                                    }));
                                  }),
                            TextSpan(
                                text: '《用户协议》',
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    Navigator.of(context)
                                        .push(MaterialPageRoute(builder: (_) {
                                      return ActivityDetail(
                                        url:
                                            'https://m.douguo.com/help/vip?open=0&aggressive=QrDdqKtzWQ&clientkey=2895b5a15d4202ab&app-state=0&device=iPhone9,1&device_id=13CB3E69-C216-4B9B-A995-1946AB7B9699&imei=4926D5D3-18DB-48D7-B85A-D065350C3BA5&pset=1&sdk=14.4&timestamp=1637654506&version=7100',
                                        titleStr: '用户协议',
                                      );
                                    }));
                                  }),
                            TextSpan(
                                text: '《隐私条款》',
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    Navigator.of(context)
                                        .push(MaterialPageRoute(builder: (_) {
                                      return ActivityDetail(
                                        url:
                                            'https://m.douguo.com/help/vip?open=0&aggressive=QrDdqKtzWQ&clientkey=2895b5a15d4202ab&app-state=0&device=iPhone9,1&device_id=13CB3E69-C216-4B9B-A995-1946AB7B9699&imei=4926D5D3-18DB-48D7-B85A-D065350C3BA5&pset=1&sdk=14.4&timestamp=1637654506&version=7100',
                                        titleStr: '隐私条款',
                                      );
                                    }));
                                  }),
                          ]),
                        ),
                      )
                    ],
                  ),
                ),
              )),
        ));
  }
}
